<template>
  <div class="userBox bg-f2" id="userBig">
    <div class="bg-f2 bg-fff">
      <ul class="btn_header">
        <li>
          <el-button type="success" class="max_btn btnSizeStyle" icon="el-icon-plus" :disabled="quanxianBtns.btn1" slot="reference" @click="addItem('新增')">添加</el-button>
        </li>
        <li>
          <div class="select">
            <span>字典类别:</span>
            <el-select v-model="unitList" :no-data-text="tiText1" clearable placeholder="选择字典类别">
              <el-option v-for="item in lbmcOptions" :key="item.value" :label="item.label" :value="item.value"></el-option>
            </el-select>
          </div>
        </li>
        <li>
          <el-input v-model.trim="searchNamer" prefix-icon="el-icon-search" clearable placeholder="输入名称"></el-input>
        </li>
        <li>
          <el-button type="primary" class="max_btn2 btnSizeStyle" @click="searchBtn2()">查询</el-button>
        </li>
      </ul>
      <el-drawer title="我是标题" :visible.sync="ShowPopover" :with-header="false" :wrapperClosable="false">
        <div class="addUer_title">
          <span>{{ title }}</span>
          <i class="el-icon-close addUer_icon" @click="offDrawer('ruleForm')"></i>
        </div>
        <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="130px">
          <el-row>
            <el-col :span="23">
              <el-form-item label="名称：" prop="zwzcmc">
                <el-input v-model.trim="ruleForm.zwzcmc" clearable placeholder="填写问题或故障名称"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="23">
              <el-form-item label="字典类别" prop="zidianLX">
                <el-select v-model="ruleForm.zidianLX" :no-data-text="tiText1" clearable placeholder="选择字典类别" style="width: 260px">
                  <el-option v-for="item in lbmcOptions" :key="item.value" :label="item.label" :value="item.value"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <div class="forms_fooer">
            <el-button class="btnSizeStyle" @click="offDrawer('ruleForm')">取消</el-button>
            <el-button type="primary" class="btnSizeStyle" @click="submitForm(title, 'ruleForm')" v-preventReClick>确定</el-button>
          </div>
        </el-form>
      </el-drawer>
      <el-table
        stripe
        ref="zhankai"
        @select="isCheck"
        @select-all="isCheckAll"
        @row-dblclick="rowClick"
        :data="rolelist"
        border
        highlight-current-row
        :default-sort="{ prop: 'type', order: 'descending' }"
        :header-cell-style="{ backgroundColor: '#ECF3FC', color: '#333', height: '48px', borderBottom: '1px solid #CEE1F7' }"
        v-loading="tableLoad"
        @sort-change="sortthiscolumn"
      >
        <!-- 提示语句 -->
        <template slot="empty">{{ tableMessage }}</template>
        <el-table-column type="selection" :selectable="checkboxT"></el-table-column>
        <el-table-column type="index" label="序号" min-width="50" align="center"></el-table-column>
        <el-table-column label="名称" prop="lbmc" :show-overflow-tooltip="true"></el-table-column>
        <el-table-column label="字典类别" prop="flbmc" sortable>
          <template slot-scope="scope">
            <el-tag size="medium" :type="`${lbStyle[scope.row.flbid - 1]}`">{{ scope.row.flbmc }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="添加人" prop="createBy" width="100"></el-table-column>
        <el-table-column label="添加时间" prop="tjsj" width="150">
          <template slot-scope="scope">{{ scope.row.tjsj | dateFormat }}</template>
        </el-table-column>
        <el-table-column label="操作" align="right" width="150">
          <template slot-scope="scope">
            <el-button type="text" :disabled="quanxianBtns.btn2" size="small" @click="addItem('编辑', scope.row)">编辑</el-button>
            <span class="operation" v-show="scope.row.scbs - '' === 0 ? true : false"></span>
            <el-button v-show="scope.row.scbs - '' === 0 ? true : false" :disabled="quanxianBtns.btn3" type="text" size="small" @click="deleteItem(scope.row)" class="color_f56f6f">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-dialog title="删除" :visible.sync="dialogVisible" width="30%">
        <span>您确定要删除吗？</span>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false" class="btnSizeStyle">取 消</el-button>
          <el-button type="primary" class="btnSizeStyle" @click="deleteItem2" v-preventReClick>确 定</el-button>
        </span>
      </el-dialog>
      <div class="fooer_box">
        <div>
          <el-button type="danger" class="btnSizeStyle" size="small" :disabled="deleteAll.length > 0 ? false : true" @click="dialogVisible3 = true">批量删除</el-button>
        </div>
        <el-dialog title="批量删除" :visible.sync="dialogVisible3" width="30%">
          <span>您确定要删除吗？</span>
          <span slot="footer" class="dialog-footer">
            <el-button @click="dialogVisible3 = false" class="btnSizeStyle">取 消</el-button>
            <el-button type="primary" @click="deleteItem3" class="btnSizeStyle">确 定</el-button>
          </span>
        </el-dialog>
        <el-pagination
          background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[10, 20, 30, 50]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next"
          :total="total"
        ></el-pagination>
      </div>
    </div>
  </div>
</template>
<script>
import { yeWu } from '@/utils/allUrl.js'
import { getUrl } from '@/utils/getUrl.js'
// import { startLoading, endLoading } from '@/utils/loading.js'
import { timeLoad, tableMessageText } from '@/assets/js/setTime'
export default {
  data: function () {
    return {
      rolelist: [],
      unitList: '',
      currentPage: 1,
      pageSize: 10,
      total: 0,
      ruleForm: {
        zwzcmc: '',
        zidianLX: '',
      },
      rules: {
        zwzcmc: [
          { required: true, message: '请输入名称', trigger: 'blur' },
          { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' },
        ],
        zidianLX: [{ required: true, message: '此项为必填项', trigger: 'change' }],
      },
      ShowPopover: false, // 是否显示
      title: '',
      deleteId: '',
      dialogVisible: false,
      dialogVisible3: false, // 批量删除
      deleteAll: [], // 批量删除数组
      lbmcOptions: [], // 故障字典
      xiugaiId: '',
      zwOptions: [],
      quanxianBtns: {
        btn1: true,
        btn2: true,
        btn3: false,
      },
      tableLoad: false,
      tableTimer: null,
      tableMessage: '',
      searchNamer: '',
      lbStyle: ['', 'success', 'info', 'warning', 'danger', ''],
      tiText1: '暂无数据', // 故障字典提示
      listQuery: {
        sortby: '',
        order: '',
      },
    }
  },
  watch: {
    tableLoad(newVal, oldVal) {
      this.tableTimer = setTimeout(() => {
        if (this.tableLoad) {
          this.tableLoad = false
          this.rolelist = []
          this.tableMessage = tableMessageText
          // this.total = 0
        }
      }, timeLoad)
    },
  },
  created: function () {
    this.listQuery = {
      sortby: 'id',
      order: 'ASC',
    }
    this.getList()
    // 获取故障字典
    this.getlbmc()
    this.jurisdictionBtn()
  },
  mounted: function () {
    // startLoading(document.getElementById('userBig'))
  },
  methods: {
    // 获取按钮权限
    jurisdictionBtn() {
      const menus = JSON.parse(getUrl('jurisdiction'))
      menus.forEach((item) => {
        if (item.qxdm === 'YWZX_WTGZ_WTGZZD') {
          item.children.forEach((item2) => {
            if (item2.qxdm === 'wtgzzd:insertWenTiGuZhangZiDian') {
              this.quanxianBtns.btn1 = false // 添加
            } else if (item2.qxdm === 'wtgzzd:updateWenTiGuZhangZiDian') {
              this.quanxianBtns.btn2 = false // 修改
            } else if (item2.qxdm === 'wtgzzd:deleteMoreWenTiGuZhangZiDian') {
              this.quanxianBtns.btn3 = false // 删除
            }
          })
        }
      })
    },
    getList() {
      clearTimeout(this.tableTimer)
      this.tableLoad = true
      const params = new URLSearchParams()
      params.append('M_', this.currentPage)
      params.append('N_', this.pageSize)
      // params.append('sort', 'ASC')
      // params.append('order', 'id')
      params.append('order', this.listQuery.sortby) // 排序字段
      params.append('sort', this.listQuery.order) // DESC降序 ASC升序
      params.append('FLBISNOTNULL', 0)
      this.setList(params)
    },
    async setList(params) {
      this.deleteAll = []
      const { data: res } = await this.$http.post(`${yeWu}wtgzzd/selectWenTiGuZhangZiDian`, params)
      switch (res.code) {
        case '0000':
          this.rolelist = res.data.list
          this.total = res.data.countList
          break
        default:
          this.rolelist = []
          this.total = 0
          this.tableMessage = res.message
          break
      }
      this.tableLoad = false // 表格加载中样式
    },
    sortthiscolumn(column) {
      // 排序
      this.tableLoad = true // 加载中样式
      if (column.order === 'descending') {
        this.listQuery.sortby = column.prop.toUpperCase()
        this.listQuery.order = 'DESC' // 降序
      } else if (column.order === 'ascending') {
        this.listQuery.sortby = column.prop.toUpperCase()
        this.listQuery.order = 'ASC' // 升序
      } else {
        this.listQuery.sortby = ''
        this.listQuery.order = '' // 没有排序
      }
      this.getList()
    },
    addItem(title, scope) {
      if (scope) {
        this.xiugaiId = scope.id
        this.ruleForm = {
          zwzcmc: scope.lbmc,
          zidianLX: scope.flbid - '',
        }
      }
      this.title = title
      this.ShowPopover = true
    },
    offDrawer(ruleForm) {
      this.$refs.ruleForm.resetFields()
      this.ShowPopover = false
      this.ruleForm = {
        zwzcmc: '',
        zidianLX: '',
      }
    },
    submitForm(title, ruleForm) {
      const { zwzcmc, zidianLX } = this.ruleForm
      const params = new URLSearchParams()
      params.append('LBMC', zwzcmc)
      params.append('FLBID', zidianLX)
      this.$refs.ruleForm.validate(async (valid) => {
        if (valid) {
          if (title === '新增') {
            const { data: res } = await this.$http.post(`${yeWu}wtgzzd/insertWenTiGuZhangZiDian`, params)
            if (res.code === '0014') {
              return
            } else if (res.code !== '0000') {
              return this.$message({
                type: 'error',
                message: res.message,
                center: true,
              })
            }
            this.$message({
              type: 'success',
              message: res.message,
              center: true,
            })
            this.ShowPopover = false
            this.getList()
            this.ruleForm = {
              zwzcmc: '',
              zidianLX: '',
            }
          } else {
            const params2 = new URLSearchParams()
            params2.append('ID', this.xiugaiId)
            params2.append('LBMC', zwzcmc)
            params2.append('FLBID', zidianLX)
            const { data: res } = await this.$http.post(`${yeWu}wtgzzd/updateWenTiGuZhangZiDian`, params2)
            if (res.code === '0014') {
              return
            } else if (res.code !== '0000') {
              return this.$message({
                type: 'error',
                message: res.message,
                center: true,
              })
            }
            this.$message({
              type: 'success',
              message: res.message,
              center: true,
            })
            this.ShowPopover = false
            this.getList()
            this.ruleForm = {
              zwzcmc: '',
              zidianLX: '',
            }
          }
        } else {
          this.$message({
            type: 'error',
            message: '请填写正确的信息',
            center: true,
          })
          return false
        }
      })
    },
    deleteItem(scope) {
      this.deleteId = scope.id
      this.dialogVisible = true
    },
    // 删除
    async deleteItem2() {
      this.dialogVisible = false
      const params = new URLSearchParams()
      params.append('ids', this.deleteId)
      const { data: res } = await this.$http.post(`${yeWu}wtgzzd/deleteMoreWenTiGuZhangZiDian`, params)
      if (res.code === '0014') {
        return
      } else if (res.code !== '0000') {
        return this.$message({
          type: 'error',
          message: res.message,
          center: true,
        })
      }
      this.currentPage = 1
      this.pageSize = 10
      this.getList()
      return this.$message({
        type: 'success',
        message: res.message,
        center: true,
      })
    },
    // 多选删除
    isCheck(selection, row) {
      const arrs = []
      selection.forEach((item) => {
        arrs.push(item.id)
      })
      const s1 = new Set(arrs)
      this.deleteAll = [...s1]
    },
    isCheckAll(selection, row) {
      const arrs = []
      selection.forEach((item) => {
        arrs.push(item.id)
      })
      const s1 = new Set(arrs)
      this.deleteAll = [...s1]
    },
    // 批量删除
    async deleteItem3() {
      this.dialogVisible3 = false
      const params = new URLSearchParams()
      params.append('ids', this.deleteAll)
      const { data: res } = await this.$http.post(`${yeWu}wtgzzd/deleteMoreWenTiGuZhangZiDian`, params)
      if (res.code === '0014') {
        return
      } else if (res.code !== '0000') {
        return this.$message({
          type: 'error',
          message: res.message,
          center: true,
        })
      }
      this.currentPage = 1
      this.pageSize = 10
      this.getList()
      this.deleteAll = []
      return this.$message({
        type: 'success',
        message: res.message,
        center: true,
      })
    },
    handleSizeChange(newSize) {
      this.currentPage = 1
      this.pageSize = newSize
      this.searchBtn()
    },
    handleCurrentChange(newPage) {
      this.currentPage = newPage
      this.searchBtn()
    },
    async getlbmc() {
      clearTimeout(this.tableTimer)
      this.tableLoad = true
      const params = new URLSearchParams()
      params.append('FLBISNULL', 0)
      const { data: res } = await this.$http.post(`${yeWu}wtgzzd/selectWenTiGuZhangZiDian`, params)
      if (res.code !== '0000') {
        this.lbmcOptions = []
        this.tiText1 = res.message
      } else {
        res.data.list.forEach((item) => {
          const k = {
            value: item.id,
            label: item.lbmc,
          }
          this.lbmcOptions.push(k)
        })
      }
    },
    searchBtn2() {
      this.currentPage = 1
      this.pageSize = 10
      this.searchBtn()
    },
    // 搜索
    searchBtn() {
      clearTimeout(this.tableTimer)
      this.tableLoad = true
      const params = new URLSearchParams()
      params.append('M_', this.currentPage)
      params.append('N_', this.pageSize)
      params.append('sort', 'ASC')
      params.append('order', 'id')
      params.append('LBMC', this.searchNamer)
      if (this.unitList) {
        params.append('FLBID', this.unitList)
      } else {
        params.append('FLBISNOTNULL', 0)
      }
      this.setList(params)
    },
    rowClick(row, column, event) {
      if (row.scbs !== 1) {
        const a = this.deleteAll.findIndex((item) => item === row.id)
        if (a !== -1) {
          this.deleteAll.splice(a, 1)
          this.$refs.zhankai.toggleRowSelection(row, false)
        } else {
          this.deleteAll.push(row.id)
          const s1 = new Set(this.deleteAll)
          this.deleteAll = [...s1]
          this.$refs.zhankai.toggleRowSelection(row, true)
        }
      } else {
        return false
      }
    },
    checkboxT(row, index) {
      // 0 未生成 1已生成
      if (row.scbs === 0) {
        return true
      } else {
        return false
      }
    },
  },
}
</script>
<style lang="scss" scoped>
.userBox {
  position: relative;
  // margin-top: 15px;
  .btn_header {
    // > li:first-child {
    //   margin-left: 0;
    // }
    > li {
      display: inline-block;
      // float: left;
      margin: 0 10px 15px 0;
    }
    // height: 35px;
    // line-height: 33px;
    .select {
      > span {
        font-weight: 600;
        margin-right: 5px;
      }
      > .el-select {
        width: 200px;
      }
    }
    .search_btn {
      width: 200px !important;
    }
  }

  .el-drawer {
    .addUer_title {
      display: flex;
      justify-content: space-between;
      padding: 0 20px;
      height: 61px;
      line-height: 61px;
      border-bottom: 1px solid #ededed;
      box-shadow: 0 -1px 2px rgba(0, 0, 0, 0.8);
      > span {
        font-size: 18px;
        font-weight: 600;
      }
      .addUer_icon {
        font-size: 20px;
        font-weight: 700;
        display: flex;
        flex-flow: column;
        justify-content: center;
        cursor: pointer;
      }
    }
    .el-row {
      margin-top: 30px;
      .bg_title {
        height: 46px;
        line-height: 46px;
        text-align: center;
        background: rgba(245, 247, 250, 1);
        > span {
          color: rgba(121, 122, 123, 1);
        }
      }
      .title_from {
        padding: 0;
        margin-bottom: 10px;
      }
    }
    .forms_fooer {
      position: absolute;
      bottom: 0;
      width: 100%;
      display: flex;
      justify-content: flex-end;
      padding: 0 20px;
      box-sizing: border-box;
      align-items: center;
      height: 61px;
      line-height: 61px;
      border-top: 1px solid #ededed;
    }
  }
  .el-table {
    // margin-top: 15px;
    border: 1px solid #eaeaea;
    border-bottom: 0;
    .minImg {
      margin-right: 5px;
    }
    .operation {
      display: inline-block;
      margin: 0 5px;
      height: 10px;
      border-left: 1.5px solid #b3b3b3;
    }
  }
  .fooer_box {
    height: 48px;
    line-height: 48px;
    padding: 0 15px;
    box-sizing: border-box;
    border-top: none;
    border: 1px solid #eaeaea;
    border-top: 0;
    display: flex;
    justify-content: space-between;
    .el-pagination {
      padding: 6px 5px;
    }
  }
}
</style>
